<script setup>
// 商城首页
import {onMounted, reactive, ref, onUnmounted} from "vue";
import axios from "axios";
import Products from "@/views/Home/component/Products.vue";
import router from "@/router/index.js";
import {catMove, catFall} from "@/util/animate/animate_1.js";
import {HTTP} from "@/api/HTTP.js";
import {ElMessage} from "element-plus";


// cat动效果
catMove('.cat')

const loading = ref(false)
const products = ref([])
const categories = ref([])
const tab2 = reactive([
  {
    title: "我的优惠券",
    link: "/voucher"
  },
  {
    title: "我的订单",
    link: "/order"
  },
  {
    title: "个人中心",
    link: "/center"
  },
  {
    title: "我的购物车",
    link: "/cart"
  }])

const handleSkip = (item) => {
  loading.value = true

  setTimeout(() => {
    loading.value = false
    router.push(item.link)
  }, 1000)
}


// 分类标签数据
const tabsData = ref([])

// 请求分类数据
onMounted(() => {
  catFall('.cat')

  async function getData() {
    await HTTP.get('/item/category?categoryId=0').then((response) => {
      tabsData.value = response.data.children.map(item => ({
        id: item.categoryId,
        name: item.categoryName,
      }))
    })
  }

  getData()
})

// 退出登录返回登录页
const confirmEvent = () => {
  location.href = '/login'
  ElMessage({
    message: '退出登录成功',
    type: 'success',
  });
  // 移除token
  localStorage.removeItem('token')
  localStorage.removeItem('show')
}

// 修改属性名为 label value
function transformCategoryData(data) {
  return {
    value: data.categoryId,
    label: data.categoryName,
    children: data.children.map(child => transformCategoryData(child))
  };
}

// 选择框默认值
const form = reactive({
  OptionValue: '',
})

// 对话框 显示
const dialogFormVisible = ref(false)
const ClearData = ref({})
const handleClear = async (item) => {
    categories.value = []
  try {
    const response = await HTTP.get(`/item/category?categoryId=${item.id}`);
    response.data = transformCategoryData(response.data);
    categories.value.push(response.data)
    if (response.code === 10200) {
      ElMessage({
        message: '加载数据成功',
        type: 'success',
      });
      dialogFormVisible.value = true;
      ClearData.value = item;
    } else {
      ElMessage({
        message: '加载数据失败',
        type: 'error',
      });
    }
  } catch (error) {
    ElMessage({
      message: '加载数据失败',
      type: 'error',
    });
    console.error('加载数据失败：', error);
  }
};

// 搜索框的值
const SearchValue = ref('')
const handleSearch = async () => {
  try {
    if (!SearchValue.value) {
      ElMessage({
        message: '请输入搜索内容',
        type: 'error',
      });
      return;
    }
    const response = await HTTP.get(`/item?name=${SearchValue.value}`);
    if (response.code === 10200) {
      products.value = response.data.itemPageList;
      ElMessage({
        message: '搜索成功',
        type: 'success',
      });
      SearchValue.value = ''
    } else {
      ElMessage({
        message: '搜索失败',
        type: 'error',
      });
      SearchValue.value = ''
    }
    console.log('搜索内容：', SearchValue.value);
  } catch (error) {
    ElMessage({
      message: '搜索失败',
      type: 'error',
    });
    console.error('搜索失败：', error);
  }
};

// 处理树形选择器选项选择
const handleOption = async () => {
  console.log(form.OptionValue)
  try {

    const response = await HTTP.get(`/item?category_id=${form.OptionValue}`);

    if (response.code === 10200) {
      products.value = response.data.itemPageList;
      ElMessage({
        message: '分类选择成功',
        type: 'success',
      });
    } else {
      ElMessage({
        message: '分类选择失败',
        type: 'error',
      })
    }
  } catch (error) {
    console.error('选项选择失败：', error);
  } finally {
    dialogFormVisible.value = false
  }
}

// 锁定滚动
const lockScroll = () => {
  document.body.style.overflow = 'hidden';
};

// 解锁滚动
const unlockScroll = () => {
  document.body.style.overflow = '';
};

// 监听滚动事件 实现滚动加载
const scrollThreshold = 5; // 距离底部的距离阈值
let page = ref(1);

// 处理滚动事件
const handleScroll = (event) => {
  const {scrollTop, clientHeight, scrollHeight} = event.target;
  const distanceToBottom = scrollHeight - (scrollTop + clientHeight);
  console.log('Scroll Top:', scrollTop);

  if (distanceToBottom <= scrollThreshold && !loading.value) {
    loadMoreData(page.value);
  }
};

// 加载更多数据
const loadMoreData = async (currentPage) => {
  const size = 24
  loading.value = true
  lockScroll()
  try {
    const response = await HTTP.get(`/item?size=${size}&page=${currentPage}`);
    console.log(response.data);
    products.value = [...products.value, ...response.data.itemPageList];
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    setTimeout(() => {
      unlockScroll()
      loading.value = false;
    }, 1000)
    page.value++;
  }
};
// 获取商品数据 初始化
onMounted(async () => {
  await loadMoreData(page.value)
});

</script>

<template>
  <div v-myLoading="loading"></div>
  <div class="home" @scroll="handleScroll">
    <!--顶部 导航栏-->
    <header>
      <div class="home_head flex">
        <ul class="skip">
          <li>欢迎来到喵喵商城~</li>
          <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon-color="#626AEF"
              title="你确定要退出登录吗？"
              @confirm="confirmEvent">
            <template #reference>
              <li>退出登录</li>
            </template>
          </el-popconfirm>
        </ul>
        <ul>
          <li @click="handleSkip(item)" v-for="item in tab2" :key="item">
            {{ item.title }}
          </li>
        </ul>
      </div>
    </header>

    <!--搜索栏-->
    <nav>
      <div class="home_search flex">
        <div class="nav_logo">
          <!--logo-->
          <img src="@/assets/icon/cat.png" alt="喵喵喵" class="cat" @click="catMove">
          <ul>
            <li>收手吧</li>
            <li>阿组</li>
          </ul>
        </div>
        <div class="nav_search">
          <!-- 搜索框-->
          <div class="search">
            <input type="text" class="form-control" style="height: 48px;width:600px;border: 2px  #ccc solid"
                   id="exampleInputEmail1"
                   @keyup.enter="handleSearch"
                   v-model="SearchValue"
                   aria-describedby="emailHelp"
                   placeholder="请输入你要查询的商品">

            <button type="button" @click="handleSearch" class="btn btn-outline-secondary">
              <i class="iconfont icon-sousuo6"></i>
            </button>
          </div>

        </div>
      </div>
    </nav>
    <!--分类 导航栏-->
    <nav>
      <div class="nav_tabs">
        <ul>
          <li @click="handleClear(item)" v-for="item in tabsData" :key="item.id">
            <i class="iconfont icon-bianji"></i>
            <p>{{ item.name }}</p>
          </li>
          <!-- 对话框-->
          <el-dialog v-model="dialogFormVisible" :title="ClearData.title" width="500" height="400"
                     style="border-radius: 10px;padding: 20px">
            <el-form :model="form">
              <el-form-item label="标签" label-width="40px">
                <el-tree-select
                    @change="handleOption"
                    v-model="form.OptionValue"
                    :data="categories"
                    aria-placeholder="请选择分类"
                    :render-after-expand="false"
                    style="width:100%"
                />
              </el-form-item>
            </el-form>
          </el-dialog>
        </ul>
      </div>
    </nav>

    <!--内容主体-->
    <main class="main_contain">
      <Products :products="products"></Products>
    </main>
  </div>
</template>

<style scoped lang="scss">
.flex {
  display: flex;
  width: 100%;
}

.home {
  width: 1535px;
  height: 100vh;
  background-color: #ffdada;
  margin: 0 auto;
  overflow-y: scroll;
  overflow-x: hidden;

  .home_head {
    height: 30px;
    justify-content: space-between;
    background-color: #ffecec;

    .skip {
      width: 350px;
    }

    ul {
      width: 550px;
      display: flex;
      justify-content: space-around;

      li {
        cursor: pointer;
        line-height: 30px;
        font-weight: 500;
        text-align: center;
        width: auto;

      }
    }
  }

  .home_search {
    background-color: #fecaca;

    .nav_logo {
      display: flex;
      justify-items: center;
      position: relative;

      img {
        width: 240px;
        height: 100px;
      }

      ul {
        width: 120px;
        position: absolute;
        top: 14px;
        right: -35px;

        li {
          font-size: 25px;
          font-weight: bold;
          text-align: center;
          font-family: "微软雅黑", serif;
        }
      }
    }
  }

  .nav_search {
    margin: 30px 0 0 200px;

    .search {
      display: flex;
      width: 670px;
      justify-content: space-between;

      button {
        width: 50px;

        i {
          font-size: 21px;
          font-weight: bold;
        }
      }
    }

  }

  .nav_tabs {
    background-color: #ffb0b0;

    ul {
      display: flex;
      justify-content: space-around;
      padding: 5px;

      li {
        width: 80px;
        height: 80px;
        cursor: pointer;
        background-color: #f9c0c0;
        text-align: center;
        border-radius: 10px;

        i {
          font-size: 40px;
        }

        p {
          width: 80px;
          font-size: 14px;
          text-align: center;
        }
      }

      li:hover {
        border: 1px black solid;
      }
    }
  }

  .main_contain {
    width: 100%;
    height: auto;
    background-color: #ffdada;

  }
}

</style>